const list = [
    { id: 1, name: "root", parentId: null },
    { id: 2, name: "child1", parentId: 1 },
    { id: 3, name: "child2", parentId: 1 },
    { id: 4, name: "grandchild1", parentId: 2 },
    { id: 5, name: "grandchild2", parentId: 2 },
  ];
function arrayToTree(items){
    const result = []; // 存放结果集
    const itemMap = {}; // 存放路径

    // 先转化为map储存
    for(const item of items){
        itemMap[item.id] = {...item,children:[]};
    }
    for(const item of items){
        const id = item.id
        const parentId = item.parentId;

        const mapItem = itemMap[id];
        if(parentId === null){
            result.push(mapItem); // 根节点
        }else{
            
            // console.log('🍀base.js:25/[itemMap[parentId]]:',itemMap[parentId] )
            if(!itemMap[parentId]){
                console.log("无",parentId);
                itemMap[parentId] = {children:[]};
            }
            itemMap[parentId].children.push(mapItem);
        }
    }
    return result;
}
// 使用函数转换
const tree = arrayToTree(list);


/**
 * 翻转二叉树
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
    if(root === null){
        return ;
    }
    // 翻转左右子树
    [root.left,root.right] = [invertTree(root.right),invertTree(root.left)];
    return root;
};

let invert =  invertTree(tree);
console.log(invert);